//
//  AppDelegate.swift
//  YYWeibo
//
//  Created by strongwallyi on 15/12/26.
//  Copyright © 2015年 strongwallyi. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: YYSwitchRootViewControllerNotification, object: nil)
        
        //初始化 window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        //设置根控制器
        window?.rootViewController = YYUserAccountViewModel.sharedViewModel.userLogin ? defaultRootViewController() : YYMainViewController()
        //成为主控制器并可见
        window?.makeKeyAndVisible()
        
        return true
    }
    
    //切换控制器
    func switchRootViewController(noti: NSNotification){
        print("切换控制器")
        if noti.object == nil {
            window?.rootViewController = YYMainViewController()
        }else{
            window?.rootViewController = YYWelcomeViewController()
        }
    }
    
    //根据是否有新版本返回不同的控制器
    func defaultRootViewController() -> UIViewController{
        if hasNewVersion(){
            return YYNewFeatureViewController()
        }else{
            return YYWelcomeViewController()
        }
    }
    
    //判断是否有新版本
    func hasNewVersion() -> Bool{
        
        //从沙盒中取存版本,取出来的是沙盒里边的版本号的值
        let sanboxVersion = NSUserDefaults.standardUserDefaults().stringForKey("version")
        
        
        //获取当前的版本号
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        //保存当前的版本号
        NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "version")
        
        if sanboxVersion == nil {
            return true
        }
        
        //将当前的版本号和沙盒中的版本号进行对比
        if currentVersion.compare(sanboxVersion!) == .OrderedDescending{
            return true
        }

        return false
    }
    
    //注销通知观察者
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}

